package com.smzd.framework.sso;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smzd.framework.system.domain.User;
import com.smzd.framework.utils.ConcurrentMapUtil;
import com.smzd.framework.utils.JsonHelper;

@Controller
@RequestMapping("/sso")
public class SSOController {

    @RequestMapping("/query")
    public String ssoQuery(Map<String, Object> map, String redirect_uri, Principal principal) {
        if (redirect_uri == null || redirect_uri.trim().length() == 0) {
            return null;
        }
        if (principal == null) {
            return null;
        }
        if (principal instanceof UsernamePasswordAuthenticationToken) {
            User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
            // byte[] uuid = UUIDGenerator.randomUUID(true);
            UUID uuid = UUID.randomUUID();
            String uuidStr = uuid.toString();
            ConcurrentMapUtil.getUserConcurrentMap().put(uuidStr, user);
            if (redirect_uri.indexOf("?") > 0) {
                redirect_uri += "&ticket=" + uuidStr;
            } else {
                redirect_uri += "?ticket=" + uuidStr;
            }
            return "redirect:" + redirect_uri;
        }
        return null;
    }

    @RequestMapping("/answer")
    @ResponseBody
    public String ssoAnswer(String ticket) {
        User user = ConcurrentMapUtil.getUserConcurrentMap().remove(ticket);
        String result;
        if (user == null) {
            result = "{error: true, error_desc: 'invalid code'}";
        } else {
            result = "{\"id\": " + user.getId() + ",\"username\": \"" + user.getUsername() + "\"}";
        }
        System.out.println("--单点登录返回值：" + result);
        return result;
    }

    @RequestMapping("/userinfo")
    @ResponseBody
    public String getPhotos(Principal principal) {
        OAuth2Authentication oa = (OAuth2Authentication) principal;
        User user = (User) oa.getPrincipal();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", user.getId());
        map.put("name", user.getName());
        map.put("gender", user.getGender());
        return JsonHelper.getSuccessJsonString(map);
    }

}
